<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
            v-model="queryParams.model"
            placeholder="请输入型号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Plus" v-hasPermi="['mxerp:product:add']" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="略图" align="center" class-name="small-padding fixed-width" width="80">
        <template #default="scope">
          <el-image style="width: 70px; height: 70px" :src="scope.row.img"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="型号" align="center" prop="model"/>
      <el-table-column label="颜色" align="center" prop="color"/>
      <el-table-column label="规格" align="center" prop="gg"/>
      <el-table-column label="电池容量" align="center" prop="dianchi"/>
      <el-table-column label="供货价格" align="center" prop="price"/>
      <el-table-column label="供货商" align="center" prop="supplierName"/>
      <el-table-column label="库存" align="center" prop="wcount"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button link type="primary" icon="PictureFilled" @click="proImages(scope.row)"
                     v-hasPermi="['mxerp:product:edit']"></el-button>
          <el-button link type="primary" icon="ChatLineSquare" @click="proDetail(scope.row)"
                     v-hasPermi="['mxerp:product:edit']"></el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['mxerp:product:edit']"></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['mxerp:product:remove']"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="80%" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="商品图片" prop="img">
          <!--<el-input v-model="form.img" type="textarea" placeholder="请输入内容" />-->
          <el-upload
              class="avatar-uploader"
              action="http://192.144.201.205:1000/prod-api/mxerp/img/mx_image"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="中文标题" prop="titleCn">
          <el-input v-model="form.titleCn" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="英文标题" prop="titleEn">
          <el-input v-model="form.titleEn" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号"/>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="form.color" placeholder="请输入颜色"/>
        </el-form-item>
        <el-form-item label="规格" prop="gg">
          <el-input v-model="form.gg" placeholder="请输入规格"/>
        </el-form-item>
        <el-form-item label="电池容量" prop="dianchi">
          <el-input v-model="form.dianchi" placeholder="请输入电池容量"/>
        </el-form-item>
        <el-form-item label="供货价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入供货价格"/>
        </el-form-item>
        <el-form-item label="供货商" prop="supplier">
          <el-select v-model="form.supplier" filterable placeholder="请选择供货商" style="width:100%;">
            <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="lx">
          <el-select v-model="form.lx" filterable placeholder="请选择分类" style="width:100%;">
            <el-option
                v-for="item in fdlist"
                :key="item.id"
                :label="item.val"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="其他供货商" prop="otherSupplier" width="180">
          <el-select v-model="form.otherSupplier" multiple filterable allow-create placeholder="请输入其他供货商"
                     style="width:100%;">
            <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证书名称" prop="zs">
          <el-select v-model="form.zs" multiple filterable allow-create placeholder="请输入其他供货商" style="width:100%;">
            <el-option
                v-for="item in zslist"
                :key="item.id"
                :label="item.val"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否显示" prop="webStatus">
          <el-radio v-model="form.webStatus" label="0">否</el-radio>
          <el-radio v-model="form.webStatus" label="1">是</el-radio>
        </el-form-item>
        <el-form-item label="跳转地址" prop="url">
          <el-input v-model="form.url" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>



      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 商品详情 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="80%" append-to-body>
      <div>
        <el-divider content-position="left">商品详情</el-divider>
        <el-descriptions :column="3" border>
          <el-descriptions-item
              label="名称" label-align="right" span="2"
              align="center" label-class-name="my-label"
              class-name="my-content" >
            {{productDetail.name}}
          </el-descriptions-item>
          <el-descriptions-item label="型号" label-align="right" align="center">
            {{productDetail.model}}
          </el-descriptions-item>
          <el-descriptions-item label="中文标题" label-align="right" span="3" align="center">
            {{productDetail.titleCn}}
          </el-descriptions-item>
          <el-descriptions-item label="英文标题" label-align="right" span="3" align="center">
            {{productDetail.titleEn}}
          </el-descriptions-item>
          <el-descriptions-item label="颜色" label-align="right" align="center">
            {{productDetail.color}}
          </el-descriptions-item>
          <el-descriptions-item label="规格" label-align="right" align="center">
            {{productDetail.gg}}
          </el-descriptions-item>
          <el-descriptions-item label="电池容量" label-align="right" align="center">
            {{productDetail.dianchi}}
          </el-descriptions-item>
          <el-descriptions-item label="供货价格" label-align="right" align="center">
            {{productDetail.price}}
          </el-descriptions-item>
          <el-descriptions-item label="供货商" label-align="right" align="center">
            {{productDetail.supplierName}}
          </el-descriptions-item>
          <el-descriptions-item label="库存" label-align="right" align="center">
            {{productDetail.wcount}}
          </el-descriptions-item>
          <el-descriptions-item label="类目" label-align="right" align="center">
            {{productDetail.lxname}}
          </el-descriptions-item>
          <el-descriptions-item label="其他供货商" label-align="right" align="center">
            {{productDetail.otherSupplierName}}
          </el-descriptions-item>
          <el-descriptions-item label="证书" label-align="right" align="center">
            {{productDetail.zsName}}
          </el-descriptions-item>
          <el-descriptions-item label="图片" label-align="right" align="center">
            <el-image style="width: 70px; height: 70px" :src="productDetail.img"/>
          </el-descriptions-item>
          <el-descriptions-item label="备注" span="2" label-align="right" align="center">
            {{productDetail.remark}}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">仓库库存</el-divider>
        <el-table :data="warelist" >
          <el-table-column label="略图" align="center" class-name="small-padding fixed-width" width="80" >
            <template #default="scope">
              <el-image style="width: 70px; height: 70px" :src="scope.row.img" />
            </template>
          </el-table-column>
          <el-table-column label="颜色" align="center" prop="color" />
          <el-table-column label="规格名称" align="center" prop="gg_name" />
          <el-table-column label="条码" align="center" prop="code" />
          <el-table-column label="供货价格" align="center" prop="price" />
          <el-table-column label="库存" align="center" prop="inventory" />
        </el-table>


        <el-divider content-position="left">tiktok-shop</el-divider>
        <el-table :data="tkshoplist" >
          <el-table-column label="商品" align="center" prop="name" />
          <el-table-column label="SPU" align="center" prop="spu" />
          <el-table-column label="店铺" align="center" prop="dianpu" />
          <el-table-column label="进货价格" align="center" prop="price" />
          <el-table-column label="售价" align="center" prop="outprice" />
          <el-table-column label="规格" align="center" prop="ggname" />
          <el-table-column label="状态" align="center" prop="status" />
          <el-table-column label="美国" align="center" prop="us" >
            <template #default="scope">
              <el-switch inline-prompt active-text="在售" :active-value=1 active-color="#2fa1f1"
                         inactive-text="下架" :inactive-value=0 inactive-color="#9c9c9c"
                         v-model="scope.row.us" />
            </template>
          </el-table-column>
          <el-table-column label="英国" align="center" prop="uk" >
            <template #default="scope">
              <el-switch inline-prompt active-text="在售" :active-value=1 active-color="#2fa1f1"
                         inactive-text="下架" :inactive-value=0 inactive-color="#9c9c9c"
                         v-model="scope.row.uk" />
            </template>
          </el-table-column>
          <el-table-column label="沙特" align="center" prop="shate" >
            <template #default="scope">
              <el-switch inline-prompt active-text="在售" :active-value=1 active-color="#2fa1f1"
                         inactive-text="下架" :inactive-value=0 inactive-color="#9c9c9c"
                         v-model="scope.row.shate" />
            </template>
          </el-table-column>
        </el-table>

        <el-divider content-position="left">供货商</el-divider>
        <el-descriptions :column="3" border>
          <el-descriptions-item
              label="供货商" label-align="right" span="2"
              align="center" label-class-name="my-label"
              class-name="my-content" >
            {{supplierData.name}}
          </el-descriptions-item>
          <el-descriptions-item label="联系人" label-align="right" align="center">
            {{supplierData.lxr}}
          </el-descriptions-item>
          <el-descriptions-item label="地址" span="2" label-align="right" align="center">
            {{supplierData.address}}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式" label-align="right" align="center">
            {{supplierData.phone}}
          </el-descriptions-item>
          <el-descriptions-item label="图片" label-align="right" align="center">
            <el-image style="width: 70px; height: 70px" :src="supplierData.wz"/>
          </el-descriptions-item>
          <el-descriptions-item label="备注" span="2" label-align="right" align="center">
            {{supplierData.remark}}
          </el-descriptions-item>
          <el-descriptions-item label="微信" label-align="right" align="center">
            {{supplierData.wx}}
          </el-descriptions-item>
          <el-descriptions-item label="简称" label-align="right" align="center">
            {{supplierData.jcname}}
          </el-descriptions-item>
        </el-descriptions>
      </div>


    </el-dialog>


    <!-- 商品图片详情 -->
    <el-dialog title="商品图片" v-model="imgOpen" width="80%" append-to-body>

      <el-divider content-position="left">商品介绍图</el-divider>
      <div class="demo-image">
        <div v-for="(item,index) in oImglist" :key="item.id" class="block">
          <el-image style="width: 100px; height: 100px" :src="item.img" fit="full" />
        </div>
        <div class="block">
          <el-upload
              class="avatar-uploader"
              action="http://192.144.201.205:1000/prod-api/mxerp/img/mx_image"
              :show-file-list="true"
              :on-success="handleAvatarOneSuccess"
              :before-upload="beforeAvatarOneUpload">
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
      </div>




      <el-divider content-position="left">商品详情图</el-divider>
      <div class="demo-image">
        <div v-for="(item,index) in tImglist" :key="item.id" class="block">
          <el-image style="width: 100px; height: 100px" :src="item.img" fit="full" />
        </div>
        <div class="block">
          <el-upload
              class="avatar-uploader"
              action="http://192.144.201.205:1000/prod-api/mxerp/img/mx_image"
              :show-file-list="true"
              :on-success="handleAvatarTwoSuccess"
              :before-upload="beforeAvatarTwoUpload">
            <el-icon class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
      </div>



    <!--
      <el-upload
          class="avatar-uploader"
          action="http://192.144.201.205:1000/prod-api/mxerp/img/mx_image"
          :show-file-list="true"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          limit="20">
        <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    -->
    </el-dialog>

  </div>
</template>

<script setup name="Product">
import { ref } from 'vue'
import {listProduct, getProduct, delProduct, addProduct, updateProduct, getProductDetail, queryWareAndTk} from "@/api/mxerp/product";
import { getSupplier } from "@/api/mxerp/supplier";
import {allsupplier} from "@/api/mxerp/supplier";
import {ElMessage} from "element-plus";
import {getParamByPid} from "@/api/bydll/param";
import { listProductimg, getProductimg, addProductimg, getProductListimg } from "@/api/mxerp/productimg";

const {proxy} = getCurrentInstance();

const imageUrl = ref('');
const productList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const supplierList = ref([]);
const fdlist = ref([]);
const zslist = ref([]);
const detailTitle = ref("商品详情");
const detailOpen = ref(false);
// 图片上传参数
const imgOpen = ref(false);
const productId = ref(""); // 商品ID
const oImglist = ref([]);
const tImglist = ref([]);

const data = reactive({
  form: {},
  imgform: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    name: null,
    titleCn: null,
    titleEn: null,
    model: null,
    color: null,
    gg: null,
    dianchi: null,
    price: null,
    supplier: null,
    img: null,
    lx: null,
    otherSupplier: null,
    zs: null,
    lxname: null,
    supplierName: null,
    otherSupplierName: null,
    zsName: null,
    webStatus: null,
    url: null
  },
  rules: {},
  productDetail: {},
  supplierData: {},
  warelist: {},
  tkshoplist: {}
});

const {queryParams, form, rules, productDetail, supplierData, warelist, tkshoplist, imgform} = toRefs(data);

/** 查询商品管理列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


// 详情
function proDetail(row) {
  var id = row.id;
  var supplier_id = row.supplier;
  queryWareAndTk(row).then(resp => {
    warelist.value = resp.data.listWare;
    tkshoplist.value = resp.data.listTkShop;
  })

  getSupplier(supplier_id).then(response => {
    supplierData.value = response.data;
  })

  getProductDetail(id).then(resp => {
    productDetail.value = resp.data;
    detailOpen.value = true;
  });
}

function getSelData() {
  allsupplier().then(response => {
    // console.log(JSON.stringify(response.data));
    supplierList.value = response.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    titleCn: null,
    titleEn: null,
    model: null,
    color: null,
    gg: null,
    dianchi: null,
    remark: null,
    price: null,
    supplier: null,
    img: null,
    lx: null,
    otherSupplier: null,
    zs: null,
    lxname: null,
    supplierName: null,
    otherSupplierName: null,
    zsName: null,
    webStatus: null,
    url: null
  };
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProduct(_id).then(response => {
    console.log(JSON.stringify(response.data));
    form.value = response.data;
    imageUrl.value = response.data.img;
    open.value = true;
    form.value.supplier = parseInt(response.data.supplier)
    form.value.lx = parseInt(response.data.lx)


    /******************其他供货商*********进行处理多选的问题***********************************/
    let otherSupplier = form.value.otherSupplier;
    if(otherSupplier != ""){
      otherSupplier = otherSupplier.replace("[", "").replace("]", "");
      let otherSupplierlist = otherSupplier.split(",");
      let otherSuppliervalue = [];
      if (otherSupplierlist.length > 1) {
        for (var i = 0; i < otherSupplierlist.length; i++) {
          // console.log();
          otherSuppliervalue[i] = parseInt(otherSupplierlist[i]);
        }
        form.value.otherSupplier = otherSuppliervalue;
      } else {
        otherSuppliervalue[0] = parseInt(otherSupplier);
        form.value.otherSupplier = otherSuppliervalue;
      }
    }

    /******************证书名称*********进行处理多选的问题***********************************/
    let zs = form.value.zs;
    if(zs != ""){
      zs = zs.replace("[", "").replace("]", "");
      let zslist = zs.split(",");
      let zsvalue = [];
      if (zslist.length > 1) {
        for (var i = 0; i < zslist.length; i++) {
          // console.log();
          zsvalue[i] = parseInt(zslist[i]);
        }
        form.value.zs = zsvalue;
      } else {
        zsvalue[0] = parseInt(zs);
        form.value.zs = zsvalue;
      }
    }


    title.value = "修改商品管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.otherSupplier = String(form.value.otherSupplier);
        form.value.zs = String(form.value.zs);
        // console.log(JSON.stringify(form.value));
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.otherSupplier = String(form.value.otherSupplier);
        form.value.zs = String(form.value.zs);
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商品管理编号为"' + _ids + '"的数据项？').then(function () {
    return delProduct(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mxerp/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

function getFdSel() {
  var param = {"pid": "23"};
  getParamByPid(param).then(resp => {
    // console.log(JSON.stringify(resp.data));
    fdlist.value = resp.data
  })
}

function getzsSel() {
  var param = {"pid": "27"};
  getParamByPid(param).then(resp => {
    // console.log(JSON.stringify(resp.data));
    zslist.value = resp.data
  })
}

getzsSel();
getFdSel();
getSelData();
getList();

/*************商品banner详情图片***************/
const handleAvatarOneSuccess = (response, uploadFile) => {
  imgform.value.status = "0";
  imgform.value.img = uploadFile.response.imgUrl;
  addImgForm();
}
const beforeAvatarOneUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage('图片仅支持jpg格式的图片！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不能大于5MB!')
    return false
  }
  return true
}




const handleAvatarTwoSuccess = (response, uploadFile) => {
  imgform.value.status = "1";
  imgform.value.img = uploadFile.response.imgUrl;
  addImgForm();
}
const beforeAvatarTwoUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage('图片仅支持jpg格式的图片！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不能大于5MB!')
    return false
  }
  return true
}



function addImgForm() {
  addProductimg(imgform.value).then(response => {
    proxy.$modal.msgSuccess("新增成功");
    getProImages(productId.value);
  });
}

function proImages(row){
  productId.value = row.id;
  var _id = row.id;
  getProductListimg(_id).then(resp => {
    console.log(JSON.stringify(resp));
    oImglist.value = resp.data.olist
    tImglist.value = resp.data.tlist
    imgform.value.productId = row.id;
    imgOpen.value = true;
  });
}

function getProImages(_id){
  getProductListimg(_id).then(resp => {
    oImglist.value = resp.data.olist
    tImglist.value = resp.data.tlist
  });
}




/****上传图片***/
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage('图片仅支持jpg格式的图片！')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片不能大于5MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = uploadFile.response.imgUrl;
  form.value.img = uploadFile.response.imgUrl;
}


</script>


<!-- 上传图片的css样式 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
}
</style>


<style scoped>
.my-label {
  background: var(--el-color-success-light-9);
  width:80px;
}

.my-content {
  background: var(--el-color-danger-light-9);
}
</style>


<style scoped>
.demo-image .block {
  padding: 30px 0;
  text-align: center;

  display: inline-block;
  width: 10%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image .block:last-child {
  border-right: none;
}
.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
